//
//  YsNoteSDKNotebookVc.m
//  YsNoteSDK
//
//  Created by 宋宏康 on 2020/3/21.
//

#import "YsNoteSDKNotebookVc.h"
#import "YsNoteSDKNoteBookCell.h"
#import "YsNoteSDKNoteBookModel.h"
#import "YsNoteSDKNotebookViewModel.h"
#import "YsNoteSDKTools.h"
#import "YsNoteSDKRealmToos.h"
#import "YsNoteSDKHeader.h"
#import "YsNoteSDKDotModel.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import <YsRealmTools/YsRealmTools.h>
#import <YsToolsManager/YsToolsManager.h>
#import <YYKit/YYKit.h>
#import <Masonry/Masonry.h>
#import <SSZipArchive/SSZipArchive.h>
#import <YsToolsManager/NSString+YsToolsManagerQMUI.h>
@interface YsNoteSDKNotebookVc ()
 <UICollectionViewDelegate, UICollectionViewDataSource>

@property(nonatomic, strong) UICollectionView * collectionView;

@property(nonatomic, strong) NSArray <YsNoteSDKNoteBookModel *> *dataSourceArray;

@property(nonatomic, strong) YsNoteSDKNotebookViewModel * viewModel;

@property (nonatomic) dispatch_group_t group;

@end

@implementation YsNoteSDKNotebookVc

- (void)setupNavigationItems
{
    [super setupNavigationItems];
    self.title = @"硕云笔记";
}

- (void)initSubviews
{
//    NSUserDefaults *defaults = YSUserDefaults;
//    if (![defaults objectForKey:@"isFirstInstall"]) {
//        [SHKCloudNoteWelcomeView showCloudNoteWelcomeViewInKeyWindow];
//        [defaults setObject:@"1" forKey:@"isFirstInstall"];
//    }

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 24;
    layout.minimumInteritemSpacing = 20;
    layout.sectionInset = UIEdgeInsetsMake(33, 20, 65, 20);
    CGFloat itemWidth = (kScreenWidth - 20 - 20 - 20) / 2.0;
    CGFloat itemHeight = 83.0 / 158 * (kScreenWidth - 20 - 20 - 20) / 2.0;
    layout.itemSize = CGSizeMake(itemWidth, itemHeight);
    UICollectionView *collectionView =
    [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    collectionView.backgroundColor = UIColor.whiteColor;
    self.collectionView = collectionView;
    collectionView.delegate = self;
    collectionView.dataSource = self;
    self.collectionView = collectionView;
    [collectionView registerClass:YsNoteSDKNoteBookCell.class forCellWithReuseIdentifier:YsNoteSDKNoteBookCell.className];
    [self.view addSubview:collectionView];
    
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
}

- (void)initData
{
    [self fetchData];
}

- (void)bind
{
//    RAC(self.viewm, text) = self.textField.rac_textSignal;
    self.viewModel.page_size = @"20";
    self.viewModel.book_fkcode  = @"";
    self.viewModel.note_type = @"2";
}

#pragma mark - collectionViewDelegate && datasouce

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return  self.dataSourceArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YsNoteSDKNoteBookCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:YsNoteSDKNoteBookCell.className forIndexPath:indexPath];
    cell.noteBookModel = self.dataSourceArray[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    YsNoteSDKNoteBookModel *noteBookModel = self.dataSourceArray[indexPath.row];
    if ([noteBookModel.book_type intValue] > 100 ||
        [noteBookModel.book_type intValue] == 3 ||
        [noteBookModel.book_type intValue] == 6) {
//        [self alertViewWithTitle:@"提示"
//                     withMessage:@"笔记正在订制中，敬请期待"
//                     withSureMsg:@"确定"
//                   withCancelMsg:nil
//                       sureBlock:^{
//                       }];
        return;
    }
//    SHKCloudNoteListViewController *cloudNoteListViewController = [[SHKCloudNoteListViewController alloc] init];
//    cloudNoteListViewController.dataSourceArray = self.dataSourceArray;
//    cloudNoteListViewController.cloudNoteModel = cloudNoteModel;
//    cloudNoteListViewController.title = cloudNoteModel.book_name;
//    [self.navigationController pushViewController:cloudNoteListViewController animated:YES];
}

#pragma mark - fetch
- (void)fetchData
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[self.viewModel.userGetNoteBooks flattenMap:^__kindof RACSignal * _Nullable(id  _Nullable value) {
        self.dataSourceArray = [NSArray modelArrayWithClass:YsNoteSDKNoteBookModel.class json:value];
              NSDictionary *iconDic = [YsNoteSDKTools getLocalFileContentForResource:@"YsNoteSDKCloudNote" ofType:@"json"];
              [self.dataSourceArray enumerateObjectsUsingBlock:^(YsNoteSDKNoteBookModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                  obj.book_icon = [iconDic objectForKey:obj.book_type];
                 obj.smallbook_icon = [iconDic objectForKey:obj.book_name];
              }];
              [[self.dataSourceArray qmui_filterWithBlock:^BOOL(YsNoteSDKNoteBookModel *item) {
                  return [item.book_type isEqualToString:@"104"] || [item.book_type isEqualToString:@"106"];
              }] enumerateObjectsUsingBlock:^(YsNoteSDKNoteBookModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                  if ([obj.book_type isEqualToString:@"104"]) {
                      obj.book_type = @"1";
                  }else if ([obj.book_type isEqualToString:@"106"]){
                      obj.book_type = @"0";
                  }
              }];
              [self.collectionView reloadData];
        return self.viewModel.getUserNoteBookList;
    }] subscribeNext:^(id  _Nullable x) {
        NSLog(@"xx:%@",x);
        [self specialNoteSaveRealmWithArray:x];
    } error:^(NSError * _Nullable error) {
        NSLog(@"fsfsdfsdf");
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } completed:^{
        
    }];
}


#pragma mark - realm helper
- (void)specialNoteSaveRealmWithArray:(NSArray <NSDictionary *> *)speciaArray
{
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_main_queue();
    self.group = group;
    [speciaArray enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
          YsNoteSDKNoteListRealmModel *noteRealModel =  [YsNoteSDKRealmToos queryNoteByNote_fkcode:obj[@"note_fkcode"]];
           if (noteRealModel) { /// 笔记存在
               dispatch_group_async(group, queue, ^{
                   dispatch_group_enter(group);
                   [self updateNoteDotDataBynoteListModel:noteRealModel];
               });
           }else{ ///笔记不存在
               noteRealModel = [YsNoteSDKNoteListRealmModel modelWithJSON:obj];
               noteRealModel.userID = kaccountCode;
               noteRealModel.book_type =
               [[self.dataSourceArray qmui_filterWithBlock:^BOOL(YsNoteSDKNoteBookModel *item) {
                   return [item.book_fkcode isEqualToString:obj[@"note_book_fkcode"]];
               }].lastObject valueForKey:@"book_type"];
               [YsRealmToolsManager writeObj:noteRealModel];
               dispatch_group_async(group, queue, ^{
                     dispatch_group_enter(group);
                     [self updateNoteDotDataBynoteListModel:noteRealModel];
                 });
           }
    }];
    
    dispatch_group_notify(group, queue, ^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    });
}

- (void)updateNoteDotDataBynoteListModel:(YsNoteSDKNoteListRealmModel *)noteListModel
{
    NSString *downloadPath = [[YsToolsManagerFileUtil getDocumentsPath]
                               stringByAppendingPathComponent:[NSString stringWithFormat:@"AppCache/%@/%@/download",kaccountCode,noteListModel.noteID]];
     NSString *previewPicturePath = [[YsToolsManagerFileUtil getDocumentsPath]
                                     stringByAppendingPathComponent:[NSString stringWithFormat:@"AppCache/%@/%@/PreviewPicture",kaccountCode,noteListModel.noteID]];
     
     [YsToolsManagerFileUtil createDirectory:previewPicturePath];
     [YsToolsManagerFileUtil createDirectory:downloadPath];
    [[self.viewModel downloadCloudSpaceYsnoteZipWithUuid:noteListModel.ys_uuid path:downloadPath] subscribeNext:^(id  _Nullable x) {
        [SSZipArchive unzipFileAtPath:[x path] toDestination:previewPicturePath];
        [YsRealmToolsManager updateObj:^{
             noteListModel.localImagePath = previewPicturePath;
             noteListModel.localZipPath = [x path];
         }];
        /// 解压成功，写入到数据库了
        [self writeDotToRealmWithnoteListModel:noteListModel];
    } error:^(NSError * _Nullable error) {
        NSLog(@"下载失败了");
    } completed:^{
        
    }];
    
}

- (void)writeDotToRealmWithnoteListModel:(YsNoteSDKNoteListRealmModel *)noteListModel
{
    NSString *path = [NSString stringWithFormat:@"%@/%@",noteListModel.localImagePath,@"location"];
    NSString *localData = [YsNoteSDKTools getLocalFileContentDataWithPath:path];
    NSArray <NSString *> *localDataArray = [localData componentsSeparatedByString:@"\n"];
    NSDictionary <NSString *,NSMutableArray *> *dict = [YsNoteSDKTools getDotOrderDataDicWithlocalDataArray:localDataArray];
    [dict enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSMutableArray * _Nonnull obj, BOOL * _Nonnull stop) {
        BOOL isContain = [[noteListModel.pageTableArray valueForKey:@"pageId"] containsObject:[NSNumber numberWithString:key]];
        if (isContain) {
            NSUInteger index = [[noteListModel.pageTableArray valueForKey:@"pageId"] indexOfObject:[NSNumber numberWithString:key]];
            YsNoteSDKPageTable *pageTable = [noteListModel.pageTableArray objectAtIndex:index];
            /// 先删除再覆盖
            [YsRealmToolsManager deleteObjs:(NSArray<YsRealmToolsBaseModel *> *)pageTable.dotTableArray];
            [[RLMRealm defaultRealm] transactionWithBlock:^{
                [YsNoteSDKPageTable createOrUpdateInDefaultRealmWithValue:@{@"pageTableID":@(pageTable.pageTableID),@"ys_orderiId":@(pageTable.ys_orderiId),@"dotTableArray":obj}];
              }];
        }else{
            YsNoteSDKPageTable *pageTable = [[YsNoteSDKPageTable alloc] init];
            pageTable.pageTableID = pageTable.incrementaID;
            pageTable.pageId = [key intValue];
            pageTable.dotTableArray = [obj copy];
            pageTable.ys_orderiId = [YsNoteSDKTools getPageTableLatesOrdertWithNoteID:noteListModel.noteID];
            [YsRealmToolsManager updateObj:^{
                [noteListModel.pageTableArray addObject:pageTable];
            }];
        }
    }];
    dispatch_group_leave(self.group);
}

#pragma mark - getter\ setter

- (YsNoteSDKNotebookViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [[YsNoteSDKNotebookViewModel alloc] init];
    }
    return _viewModel;
}
@end
